using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using EIMS.Models.Identity;
using EIMS.Models;
using System.Diagnostics;

namespace EIMS.Data
{
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
            // 优化查询编译
            ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
            
            // 开发环境监控
            #if DEBUG
            ChangeTracker.StateChanged += (sender, e) => 
                Debug.WriteLine($"实体: {e.Entry.Entity.GetType().Name}, 状态: {e.Entry.State}");
            
            ChangeTracker.Tracked += (sender, e) => 
                Debug.WriteLine($"实体: {e.Entry.Entity.GetType().Name}, 状态: {e.Entry.State}");
            #endif
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            
            // 启用批量更新
            optionsBuilder
                .EnableDetailedErrors(false)
                .EnableSensitiveDataLogging(false);
        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            
            // 优化索引
            builder.Entity<ApplicationUser>()
                .HasIndex(u => u.Email);
            
            builder.Entity<ApplicationUser>()
                .HasIndex(u => u.UserName);
                
            // 可以在这里进行其他实体配置
            
            // 使用批量配置优化加载性能
            foreach (var entityType in builder.Model.GetEntityTypes())
            {
                // 配置软删除过滤器(如果需要)
                // 配置全局查询过滤器
                // 配置级联删除策略等
            }
        }

        // 员工管理相关实体
        public DbSet<Department> Departments { get; set; }
        public DbSet<Employee> Employees { get; set; }
        public DbSet<EmployeeHistory> EmployeeHistories { get; set; }
        
        // 客户与供应商管理相关实体
        public DbSet<Customer> Customers { get; set; }
        public DbSet<CustomerContact> CustomerContacts { get; set; }
        public DbSet<CustomerTransaction> CustomerTransactions { get; set; }
        public DbSet<Supplier> Suppliers { get; set; }
        public DbSet<SupplierContact> SupplierContacts { get; set; }
        public DbSet<SupplierTransaction> SupplierTransactions { get; set; }
    }
} 